<template>
  <div style="padding-top: 5px;">
    <el-button v-if="!surgeryApplyInfo.orderIds" class="mb5" plain type="primary" @click="handleAdd">
      <template #icon>
        <i-ep-plus/>
      </template>
      新增
    </el-button>
    <el-button class="mb5" type="primary" @click="getList">
      <template #icon>
        <i-ep-search/>
      </template>
      刷新
    </el-button>
    <el-table :border="true" :data="surgeryApplyDetailList" :header-cell-style="$headerCellStyle" :stripe="true" height="280px"
              highlight-current-row>
      <el-table-column :align="'center'" label="手术名称" min-width="200" prop="surgeryName">
        <template #default="scope">
          <template v-if="scope.row.ordersId && !scope.row.isEdit">
            <span> {{ scope.row.surgeryName }}</span>
          </template>
          <automatic-completion v-else :ref="(el:any) => setItemAutomaticRef(el, scope.$index)" :dict-array="dictArray"
                                :table-body-list="tableBodyList" :table-head-list="tableHeadList" :title="itemTitle"
                                :width="900" style="width: 100%;"
                                @itemNameInput="itemNameInput($event, scope.$index, scope.row)"
                                @rowClick="rowClick($event, scope.$index, scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="手术编码" prop="surgeryCode" width="160">
        <template #default="scope">
          <template v-if="scope.row.ordersId && !scope.row.isEdit">
            <span> {{ scope.row.surgeryCode }}</span>
          </template>
          <span v-else> {{ scope.row.surgeryCode }}</span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="手术等级" prop="surgeryScale" width="120">
        <template #default="scope">
          <template v-if="scope.row.ordersId && !scope.row.isEdit">
            <dict-data-tag :options="dictDataMap['operation_grade']" :value="scope.row.surgeryScale"/>
          </template>
          <template v-else>
            <el-select v-model="scope.row.surgeryScale" placeholder="请选择" style="width: 100%;">
              <el-option v-for="dict in dictDataMap['operation_grade']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </template>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="切口等级" prop="incisionGrade" width="120">
        <template #default="scope">
          <template v-if="scope.row.ordersId && !scope.row.isEdit">
            <dict-data-tag :options="dictDataMap['incision_grade']" :value="scope.row.surgeryScale"/>
          </template>
          <template v-else>
            <el-select v-model="scope.row.incisionGrade" placeholder="请选择" style="width: 100%;">
              <el-option v-for="dict in dictDataMap['incision_grade']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </template>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="手术序号" prop="sort" width="120">
        <template #default="scope">
          <template v-if="scope.row.ordersId && !scope.row.isEdit">
            <span> {{ scope.row.sort }}</span>
          </template>
          <el-input v-else v-model="scope.row.sort" type="number"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="术备科室" width="120">
        <template #default="scope">
          <template v-if="scope.row.ordersId && !scope.row.isEdit">
            <span> {{ scope.row.surgeryPrepareDeptName }}</span>
          </template>
          <template v-else>
            <base-dept-tree ref="baseDeptTreeRef" :clinicalSignStr="'5,6,9,10'" :org-id="props.orgId"
                            :value="scope.row.surgeryPrepareDeptId"
                            style="width: 100%" @deptSelect="surgeryPrepareCharge($event,scope.row,scope.$index)"/>
          </template>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="主刀医生" width="120">
        <template #default="scope">
          <template v-if="scope.row.ordersId && !scope.row.isEdit">
            <span> {{ scope.row.lordKnifeDoctorName }}</span>
          </template>
          <template v-else>
            <user-select-by-group-dept :id="scope.row.lordKnifeDoctorId"
                                       :ref="(el:any) => setUserSelectRef(el, scope.$index)" :org-id="props.orgId"
                                       style="width: 100%"
                                       @userChange="userChange($event,scope.row,scope.$index)"/>
          </template>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="助手" width="120">
        <template #default="scope">
          <template v-if="scope.row.ordersId && !scope.row.isEdit">
            <span> {{ scope.row.assistantName }}</span>
          </template>
          <template v-else>
            <user-select-by-group-dept :id="scope.row.assistantId" :ref="(el:any) => setAssistantRef(el, scope.$index)"
                                       :org-id="props.orgId"
                                       style="width: 100%"
                                       @userChange="assistantChange($event,scope.row,scope.$index)"/>
          </template>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="备注" prop="remarks">
        <template #default="scope">
          <template v-if="scope.row.ordersId && !scope.row.isEdit">
            <span> {{ scope.row.remarks }}</span>
          </template>
          <el-input v-else v-model="scope.row.remarks"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" fixed="right" label="操作" width="80">
        <template #default="scope">
          <template v-if="!scope.row.ordersId && !scope.row.isEdit">
            <el-tooltip class="item" content="删除" effect="dark" placement="top">
              <el-button type="danger" @click="handleDelete(scope.row)">
                <template #icon>
                  <i-ep-delete/>
                </template>
              </el-button>
            </el-tooltip>
          </template>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script lang="ts" setup>
import {useDictStoreHook} from '@/store/modules/dict'
import {useUserStoreHook} from '@/store/modules/user'
import {listSurgeryApplyDetail} from "@/api/surgery/surgeryApplyDetail.ts"
import {getAutoOperationByApply} from "@/api/base/operationDict"
import {jsonStrInObj, surgeryList} from "@/utils/autoComplete"

const {proxy} = getCurrentInstance() as any;
const dictStore = useDictStoreHook()
const userStore = useUserStoreHook()
let dictDataMap = ref(dictStore.isTypeGetData('operation_grade', 'incision_grade'))
const surgeryApplyDetailList = ref<any[]>([])
const form = ref<any>({})
// const itemAutomatic = ref()
// 创建一个ref数组来存储每个automatic-completion实例
const itemAutomaticRefs = ref<any[]>([]);

// 在模板中使用动态ref
function setItemAutomaticRef(el, index) {
  if (el) {
    itemAutomaticRefs.value[index] = el;
  }
}

// 主刀医生refs
const userSelectRefs = ref<any[]>([])

function setUserSelectRef(el, index) {
  if (el) {
    userSelectRefs.value[index] = el;
  }
}

// 助手refs
const assistantRefs = ref<any[]>([])

function setAssistantRef(el, index) {
  if (el) {
    assistantRefs.value[index] = el;
  }
}

// 项目选择自动补全窗体名称
const itemTitle = ref('手术选择')
// 项目选择自动补全表格表头
const tableHeadList = ref<any>(jsonStrInObj(surgeryList))
// 项目选择自动补全表格数据
const tableBodyList = ref<any>([])
// 项目选择自动补全字典数组
const dictArray = ref(['operation_grade'])


const props = defineProps({
  surgeryApplyInfo: {
    type: Object,
    default: {},
  },
  orgId: {
    type: String,
    default: "",
  },
})

/** 查询手术申请明细列表 */
function getList() {
  listSurgeryApplyDetail({
    applyId: props.surgeryApplyInfo.surgeryApplyId,
  }).then((response: any) => {
    surgeryApplyDetailList.value = response.data;
  });
}

/** 新增手术 */
function handleAdd() {
  if (surgeryApplyDetailList.value.length > 0) {
    if (!surgeryApplyDetailList.value[surgeryApplyDetailList.value.length - 1].surgeryName) {
      return ElMessage.error("请先选择手术后，再新增")
    }
  }
  surgeryApplyDetailList.value.push({
    isEdit: true,
    surgeryApplyDetailId: '',
    sort: surgeryApplyDetailList.value.length + 1,
    surgeryScale: "1",
    incisionGrade: "1"
  })
}


/** 项目名称自动补全检索 */
function itemNameInput(e: any, index: number, _row: any) {
  surgeryApplyDetailList.value[index].itemName = e
  getAutoOperationByApplyFun(index)
}

function getAutoOperationByApplyFun(index: number) {
  const param = {
    operationFlag: '0',
    orgId: props.orgId,
    itemInfo: surgeryApplyDetailList.value[index].itemName
  }
  getAutoOperationByApply(param).then(res => {
    tableBodyList.value = res.data
    itemAutomaticRefs.value[index].init()
  })
}

/** 手术自动补全点击事件 */
function rowClick(e: any, index: number, _row: any) {
  nextTick(() => {
    if (e) {
      nextTick(() => {
        itemAutomaticRefs.value[index].setItemName(e.operationName)
        itemAutomaticRefs.value[index].closePopover()
      })
      surgeryApplyDetailList.value[index].itemInfo = e.operationName
      surgeryApplyDetailList.value[index].surgeryName = e.operationName
      surgeryApplyDetailList.value[index].surgeryCode = e.operationCode
      surgeryApplyDetailList.value[index].orgId = e.orgId
      surgeryApplyDetailList.value[index].surgeryScale = e.operationScale
      surgeryApplyDetailList.value[index].applyId = props.surgeryApplyInfo.surgeryApplyId
      surgeryApplyDetailList.value[index].isEdit = true
    }
  })
}

function handleDelete(row: any) {
  // todo 有问题 要修改
  surgeryApplyDetailList.value = surgeryApplyDetailList.value.filter((item: any) => item.surgeryApplyDetailId !== row.surgeryApplyDetailId)
}


// 术备科室选择
function surgeryPrepareCharge(e: any, row: any, index: number) {
  row.surgeryPrepareDeptId = e.deptId || ''
  row.surgeryPrepareDeptName = e.deptName || ''
  userSelectRefs.value[index].getUserList(row.surgeryPrepareDeptId)
  assistantRefs.value[index].getUserList(row.surgeryPrepareDeptId)
}

/**
 * 主刀医生选择
 */
function userChange(e: any, row: any, index: number) {
  if (row) {
    row.lordKnifeDoctorId = e.userId;
    row.lordKnifeDoctorName = e.nickName;
  }
}

/**
 * 助手选择
 */
function assistantChange(e: any, row: any, index: number) {
  if (row) {
    row.assistantId = e.userId;
    row.assistantName = e.nickName;
  }
}

function getSurgeryList() {
  return surgeryApplyDetailList.value
}


function validateSurgeryList() {
  // 在这里实现手术列表的校验逻辑
  // 例如：检查是否已选择手术，手术信息是否完整等
  if (!surgeryApplyDetailList.value || surgeryApplyDetailList.value.length === 0) {
    ElMessage.error('请至少添加一项手术');
    return false;
  }

  // 检查每个手术项的必填信息
  for (let i = 0; i < surgeryApplyDetailList.value.length; i++) {
    const item = surgeryApplyDetailList.value[i];
    if (!item.surgeryName) {
      ElMessage.error(`第 ${i + 1} 项手术名称不能为空`);
      return false;
    }
    if (!item.surgeryCode) {
      ElMessage.error(`第 ${i + 1} 项手术编码不能为空`);
      return false;
    }
    // 可以根据实际需求添加更多的校验规则
  }

  return true;
}

// 清空列表信息
function emptyTableData() {
  surgeryApplyDetailList.value = []
}


defineExpose({
  getSurgeryList,
  validateSurgeryList,
  emptyTableData
})

onMounted(() => {
  getList()
})
</script>
